import { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import Navbar from '@/components/Navbar';
import { Location, Search } from '@nutui/icons-react-taro';
import { Image, Text, View } from '@tarojs/components';
import { Input } from '@nutui/nutui-react-taro';
import Taro, { showToast } from '@tarojs/taro';
import MapBusiness from '@/business/MapBusiness';
import './index.less';
import ImageConstant from '@/constant/ImageConstant';
import locationStore from '@/stores/LocationStore';
import { HouseEntity } from '@/entities/HouseEntity';
import LandlordBusiness from '@/business/LandlordBusiness';
import { LandlordEntity } from '@/entities/LandlordEntity';
import houseStore from '@/stores/HouseStore';
import userStore from '@/stores/UserStore';
import HouseCollectBusiness from '@/business/HouseCollectBusiness';
import systemStore from '@/stores/SystemStore';
import EmptyComp from '@/components/Empty';
import { CommonUtil } from '@/utils/CommonUtil';
import MapConstant from '@/constant/MapConstant';
import useHouse from '@/hooks/useHouse';
import HouseBusiness from '@/business/HouseBusiness';

const SlotComp = () => {
  const {setTitle, setAddress, setLongitude, setLatitude, setMinLat, setMaxLat, setMinLng, setMaxLng} = locationStore;
  const {getMarketHouseList} = useHouse();
  const handleSelectAddress = () => {
    Taro.chooseLocation({
      success(res) {
        const {address, name, latitude, longitude} = res;
        setTitle(name);
        setAddress(address);
        setLongitude(longitude);
        setLatitude(latitude);
        const {
          minLat,
          minLng,
          maxLng,
          maxLat
        } = CommonUtil.calculateCoordinatesWithinRadius(latitude, longitude, MapConstant.HOUSE_MARK_RANGE);
        setMinLat(minLat);
        setMaxLat(maxLat);
        setMinLng(minLng);
        setMaxLng(maxLng);
        // 在已选位置的基础上进行获取房屋信息
        getMarketHouseList(minLat, maxLat, minLng, maxLng);
      },
    });
  };
  return (
    <View
      onClick={ handleSelectAddress }
      className='slot-comp-container'
      id='navbar-comp'
    >
      <View className='item-wrap location-wrap'>
        <Location
          color='var(--font-first)'
          size={ 16 }
        />
        <Text className='location-text'>{ locationStore.title }</Text>
      </View>
    </View>
  );
};

const TenantMarketComp = () => {
  const {
    setEditorCurrentHouse,
    setHouseCollectList,
    houseCollectList,
    marketHouseList,
    setMarketHouseList
  } = houseStore;
  const {setCurrentLandlord} = userStore;
  // 房东列表
  const [landlordList, setLandlordList] = useState<Array<LandlordEntity.ILandlord>>([]);

  useEffect(() => {
    Taro.getFuzzyLocation({
      type: 'gcj02',
      success(res) {
        MapBusiness.getLocationName(res.latitude, res.longitude);
      },
      fail(_) {
        showToast({
          title: '获取位置失败！',
          icon: 'error'
        });
      }
    });
  }, []);

  /**
   * 获取房东信息通过房东id
   */
  const getLandlordById = async () => {
    if (marketHouseList.length) {
      const landlordIds: number[] = marketHouseList?.map(item => item.landlordId);
      // 获取房东信息
      const landlordList: any = await LandlordBusiness.getLandlordByIds([...new Set(landlordIds)].join(','));
      setLandlordList(l => [...l, ...landlordList]);
    }
  };

  /**
   * 获取房屋收藏信息
   */
  const getHouseCollectNum = async () => {
    if (marketHouseList instanceof Array && marketHouseList[0]?.houseId) {
      const collectList: any = await HouseCollectBusiness.getCollectHouseNum(
        marketHouseList.map(house => house?.houseId).join(',')!
      );
      setHouseCollectList([...houseCollectList, ...collectList]);
    }
  };
  useEffect(() => {
    getHouseCollectNum();
    getLandlordById();
  }, [marketHouseList]);

  /**
   * 获取房东信息
   * @param landlordId 房东id
   */
  const getLandlordInfo = (landlordId?: number) => {
    return landlordList?.find(item => item.id === landlordId);
  };

  /**
   * 获取房屋第一张图片
   * @param imgList
   */
  const getHouseFirstImg = (imgList: string = '') => {
    return JSON.parse(imgList)[0];
  };

  /**
   * 查看当前房屋详情信息
   * @param houses 当前房屋信息
   */
  const toHouseInfo = (houses: HouseEntity.IResultHouse) => {
    // 将当前点击查看的房屋信息存入store里面
    setEditorCurrentHouse(houses);
    // 将当前房屋的房东存储store里面
    setCurrentLandlord(getLandlordInfo(houses.landlordId));
    Taro.navigateTo({
      url: '/pages/tenantLookHouse/index',
    });
  };

  /**
   * 获取房屋通过关键字
   * @param keyword
   */
  const getHouseByKeyword = async (keyword: string) => {
    const {minLat, minLng, maxLat, maxLng} = locationStore;
    const res: any = await HouseBusiness.getHouseByKeyword({
      minLat,
      minLng,
      maxLat,
      maxLng,
      keyword
    });
    setMarketHouseList(res);
  };

  /**
   * 搜索房屋
   * @param keyWord
   */
  const searchHouse = () => {
    let timer: any;
    return (keyWord: string) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        // 发送请求获取房屋
        getHouseByKeyword(keyWord);
      }, 500);
    };
  };

  return (
    <Navbar
      isSlot={ true }
      bgColor='var(--mini-first)'
      mode='home'
      SlotComp={ SlotComp }
      className='market-container'
    >
      <View className='search-wrap'>
        <View className='input-wrap'>
          <Search
            size={ 16 }
          />
          <Input
            placeholder='房屋名称/房东名称/地址'
            onChange={ (keyWord) => searchHouse()(keyWord) }
          />
        </View>
      </View>
      <View className='market-main' style={ {height: `calc(${ systemStore.haveNavbarHaveTabbarHeight } - 40px)`} }>
        {
          marketHouseList?.length ?
            marketHouseList?.map((house: HouseEntity.IResultHouse, idx: number) => {
              return (
                <View className='market-card' key={ idx } onTap={ () => toHouseInfo(house) }>
                  <Image
                    src={ `${ ImageConstant.SERVER_ROOT }/${ getHouseFirstImg(house.houseImg) || 'female.png' }` }
                    mode='aspectFill'
                    className='card-img'
                  />
                  <View className='house-info'>
                    <View className='house-name'>{ house.name }</View>
                    <View className='info'>
                      <View className='collect'>
                        <Text>{ houseCollectList.find(c => c.houseId === house.houseId)?.count }</Text>
                        <Text>收藏</Text>
                      </View>
                      <View className='price font-bold'>
                        <Text>￥</Text>
                        <Text>{ house.price }</Text>
                        <Text>/月</Text>
                      </View>
                    </View>
                    <View className='landlord-info'>
                      <Image
                        src={ `${ ImageConstant.SERVER_ROOT }/${ getLandlordInfo(house.landlordId)?.headImg || '/common/male.png' }` }
                        className='landlord-head-img'
                      />
                      <Text className='landlord-text'>{ getLandlordInfo(house.landlordId)?.name }</Text>
                    </View>
                  </View>
                </View>
              );
            }) :
            <EmptyComp text='该地址附近暂无房屋发布，试试其他地址吧！'/>
        }
      </View>
    </Navbar>
  );
};

export default observer(TenantMarketComp);
